package com.mall.controller.sys;


import com.google.common.base.Strings;
import com.mall.entity.sys.ResEO;
import com.mall.entity.sys.UserEO;
import com.mall.exception.MsgException;
import com.mall.service.sys.IUserService;
import com.mall.utils.FTPTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Dczzs
 * @since 2020-06-24
 */
@Api(tags = "用户数据接口")
@RestController
@RequestMapping("/sys/user")
public class UserController {
	@Autowired
	private FTPTool ftpTool;


	
	@Autowired
	private IUserService service;
	
	
	
	@GetMapping("/list")
	public ResEO list() {
		ResEO res = new ResEO();
		
		List<UserEO> list = service.list();
		res.setData(list);
		
		
		return res;
		
	}
	
	@ApiOperation(value = "编辑用户",notes="根据用户ID查询当前用户完整信息")
	@ApiImplicitParam(paramType="path",name="id",value="用户ID",required=true)
	@GetMapping("/edit/{id}")
	public ResEO edit( @PathVariable Integer id) {
		ResEO res = new ResEO();
		
		try {
			UserEO eo =  service.getById(id);
			res.setData(eo); 
		} catch (Exception e) {
			e.printStackTrace();
			res.setStatus(-1); 
		}
		
		
		return res;
		
	}
	
	@PostMapping("/save")
	public ResEO save(UserEO eo, MultipartFile imgUrlFile) {
	ResEO res = new ResEO();
	
		try {
			
			if(imgUrlFile!=null) {
				// 创建文件上传核心类
						String imgUrl = eo.getImgUrl();
						
						if(Strings.isNullOrEmpty(imgUrl)) {
							imgUrl = "/" + System.nanoTime() + ".jpg";	
						}
						

						try {
							ftpTool.connect();
							ftpTool.uploadFileFromIS(imgUrl, imgUrlFile.getInputStream());
							eo.setImgUrl(imgUrl);
							System.out.println(String.format("Name = %s; Value = %s", "imgUrl",imgUrl));
						} catch (Exception e) {
							e.printStackTrace();
							res.appendMsg("附件保存失败，请编辑后重新上传，或者联系管理员&*&*&*&*&*&");
						}
				}
			
			
			
			boolean saveOrUpdate = service.saveOrUpdate(eo);
			if(saveOrUpdate) {
				res.setMsg("已保存");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			res.setStatus(-1); 
		}
		return res;
	}
	
	@GetMapping("/delete/{id}")
	public ResEO delete(@PathVariable Integer id) {
		ResEO res = new ResEO();
		
		try {
			service.delete(id);
		} catch (MsgException e) {
			e.printStackTrace();
			res.setStatus(1);
		} catch (Exception e) {
			e.printStackTrace();
			res.setStatus(-1);
		}
		
		return res;
	}
	

}
